<template>
  <div class="app-container">
    <div class="container-bg">
      <div class="filter-container">
        <el-input
          v-model="listQuery.name"
          placeholder="姓名"
          style="width: 120px"
          class="filter-item"
        />
        <el-select
          style="width: 120px"
          v-model="listQuery.iLoadComplete"
          placeholder="请选择人员状态"
          @change="doGetCommunityPersons"
          class="filter-item m-margin-l10"
        >
          <el-option
            v-for="(v, i) in personStatus"
            :key="v.value"
            :label="v.name"
            :value="v.value"
          />
        </el-select>
        <el-date-picker
          style="width: 380px"
          class="filter-item m-margin-l10"
          v-model="dateTime"
          type="datetimerange"
          :editable="false"
          range-separator="~"
          value-format="yyyy-MM-dd HH:mm:ss"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
        >
        </el-date-picker>
        <el-button
          class="filter-item m-margin-l10"
          type="primary"
          icon="el-icon-search"
          @click="onSearch"
          >查询
        </el-button>
        <el-button
          class="filter-item m-margin-l10"
          type="warning"
          @click="onReset"
          >重置
        </el-button>
        <div style="float: right; display: flex">
          <!-- <el-button type="primary" @click="uploadDialogVisible = true"
            >上传文件
          </el-button> -->
          <el-button
            class="m-margin-l10"
            icon="el-icon-edit"
            type="primary"
            @click="addCommunityPerson"
            >批量注册
          </el-button>
          <el-button
            class="m-margin-l10"
            icon="el-icon-edit"
            type="primary"
            @click="addCommunityPerson(1)"
            >单人注册
          </el-button>
        </div>
      </div>
      <div class="filter-container">
        <el-button
          icon="el-icon-delete"
          class="filter-item"
          type="danger"
          plain
          @click="doDeleteCommunityPersonSelect"
          >批量删除
        </el-button>
        <el-button
          icon="el-icon-delete"
          class="filter-item"
          type="info"
          @click="doDeleteCommunityPersonAll"
          >全部清除
        </el-button>
        <!-- <el-popconfirm
          cancel-button-text="不用了"
          confirm-button-text="好的"
          icon="el-icon-info"
          icon-color="red"
          title="您确定删除当前选中人员吗？"
          @confirm="doDeleteCommunityPerson"
        >
          <el-button
            slot="reference"
            icon="el-icon-delete"
            class="filter-item"
            type="danger"
            >批量删除
          </el-button>
        </el-popconfirm> -->
        <el-button
          class="filter-item"
          style="margin-left: 10px"
          type="success"
          @click="doDownloadFile"
          :disabled="personData.total == 0"
          >导出
        </el-button>
      </div>
      <el-table
        :data="personData.list"
        border
        fit
        highlight-current-row
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="40"></el-table-column>
        <!-- <el-table-column
          label="序号"
          prop="id"
          width="100px"
          align="center"
        ></el-table-column> -->
        <el-table-column align="center" label="照片" width="100px">
          <template slot-scope="scope">
            <el-image
              style="width: 60px; height: 60px; border-radius: 50%"
              ref="lazyImg"
              fit="cover"
              :src="localOrigin +scope.row.sLocalPicturePath"
              class="vx-lazyLoad"
              lazy
            >
              <div slot="placeholder" class="image-slot">
                <i class="el-icon-loading"></i>加载中
              </div>
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column align="center" label="姓名" show-overflow-tooltip>
          <template slot-scope="scope">{{ scope.row.sName }}</template>
        </el-table-column>
        <el-table-column align="center" label="注册状态">
          <template slot-scope="scope">
            <div>{{ scope.row.iLoadCompleted | iLoadCompleted }}</div>
            <div style="margin-top: 5px" v-if="scope.row.iLoadCompleted == -1">
              {{ scope.row.iRecoFailedCodeErrorMesg || "" }}
            </div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="类型" v-if="false">
          <template slot-scope="scope">{{ scope.row.sType | sType }}</template>
        </el-table-column>
        <el-table-column align="center" label="门禁卡号" v-if="false">
          <template slot-scope="scope">
            {{ scope.row.iAccessCardNumber }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="手机号" v-if="false">
          <template slot-scope="scope">
            {{ scope.row.sTelephoneNumber }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" label="性别">
          <template slot-scope="scope">
            <span v-show="scope.row.sGender == 'male'">男</span>
            <span v-show="scope.row.sGender == 'female'">女</span>
            <span v-show="scope.row.sGender == 'unset'">未设置</span>
          </template>
        </el-table-column> -->
        <el-table-column align="center" label="身份证" v-if="false">
          <template slot-scope="scope">{{
            scope.row.sCertificateNumber
          }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          class-name="status-col"
          label="创建时间"
          width="180"
          prop="sRegistrationTime"
        >
          <template slot-scope="scope">{{
            scope.row.sRegistrationTime
          }}</template>
        </el-table-column>
        <el-table-column
          align="center"
          class-name="status-col"
          label="操作"
          width="150"
        >
          <template slot-scope="{ row, $index }">
            <el-row>
              <el-button
                size="mini"
                class="light_blue_btn"
                @click="editCommunityPerson(row, $index)"
                >修改
              </el-button>
              <el-popconfirm
                cancel-button-text="不用了"
                class="m-margin-l10"
                confirm-button-text="好的"
                icon="el-icon-info"
                icon-color="red"
                title="您确定删除当前人员吗？"
                @confirm="doDeleteCommunityPerson"
              >
                <el-button
                  slot="reference"
                  size="mini"
                  class="light_red_btn"
                  @click="deleteCommunityPerson(row)"
                  >删除
                </el-button>
              </el-popconfirm>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        :limit.sync="listQuery.limit"
        :page.sync="listQuery.page"
        :total="personData.total"
        :page-sizes="[20, 100, 500]"
        @pagination="changePage"
      />
    </div>
    <!-- 单个添加人员 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      v-if="dialogFormVisible"
      width="740px"
      title="单人注册"
      :close-on-click-modal="false"
      @close="onClose"
    >
      <el-form
        class="el-form-box"
        ref="dataForm"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="100px"
        style="margin: 0 50px"
      >
        <el-form-item label="姓名">
          <el-input
            v-model.trim="form.sName"
            placeholder="请输入姓名"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="sTelephoneNumber" v-if="false">
          <el-input
            v-model="form.sTelephoneNumber"
            placeholder="请输入手机号码"
          />
        </el-form-item>
        <el-form-item label="身份证" prop="sCertificateNumber" v-if="false">
          <el-input
            v-model="form.sCertificateNumber"
            placeholder="请输入身份证"
          />
        </el-form-item>
        <el-form-item label="证件类型" prop="sCertificateType" v-if="false">
          <el-select
            v-model="form.sCertificateType"
            class="filter-item"
            placeholder="请选择人员证件类型"
          >
            <el-option key="identityCard" label="身份证" value="identityCard" />
          </el-select>
        </el-form-item>
        <el-form-item label="出生日期" prop="sBirthday" v-if="false">
          <el-date-picker
            v-model="form.sBirthday"
            type="date"
            placeholder="选择出生日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>
        <!-- <el-form-item label="性别" prop="sGender">
          <el-select
            v-model="form.sGender"
            class="filter-item"
            placeholder="请选择人员性别"
          >
            <el-option key="male" label="男" value="male" />
            <el-option key="female" label="女" value="female" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="人员类型" prop="sType" v-if="false">
          <el-select
            v-model="form.sType"
            class="filter-item"
            placeholder="请选择人员类型"
          >
            <el-option
              v-for="(v, i) in sTypeArr"
              :key="v.value"
              :label="v.name"
              :value="v.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="门禁卡号" prop="iAccessCardNumber" v-if="false">
          <el-input
            v-model="form.iAccessCardNumber"
            type="number"
            class="numrule"
            oninput="if(value.length>20)value=value.slice(0,20)"
            placeholder="请输入门禁卡号"
          />
        </el-form-item>
        <el-form-item label="人脸照片" style="width: 100%">
          <el-upload
            :auto-upload="false"
            :file-list="fileList"
            :limit="limitCount"
            :on-change="getFile"
            :on-remove="handleRemove"
            accept="image/jpg,image/jpeg"
            action=""
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :class="{ hide: hideUpload }"
          >
            <!-- <el-button size="small" type="primary">选择图片</el-button> -->
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传单个jpg/jpeg文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
        <!-- <el-form-item label="外部ID" prop="type">
          <el-input v-model="form.extPersonId" placeholder="请输入外部人员ID" />
        </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="saveCommunityPersonInfo()"
          :loading="singleLoading"
          >提交
        </el-button>
      </div>
    </el-dialog>
    <!-- 批量添加 -->
    <el-dialog
      :visible.sync="dialogFormGroup"
      title="批量添加"
      width="600px"
      :close-on-click-modal="false"
      v-if="dialogFormGroup"
    >
      <el-form
        ref="dataForm"
        :model="form"
        :rules="rules"
        label-position="left"
        label-width="70px"
      >
        <div class="pro-loading">
          <el-progress
            :text-inside="true"
            :stroke-width="14"
            :percentage="parseInt(percentage)"
            v-if="showprogress"
          ></el-progress>
        </div>
        <el-form-item label="文件" prop="type">
          <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            accept="image/png,image/jpg,image/jpeg"
            :on-remove="handleRemoveGroup"
            :on-change="handleSuccessGroup"
            :on-exceed="handleExceed"
            :multiple="true"
            :limit="10000"
            :file-list="fileListGroup"
            :auto-upload="false"
          >
            <el-button slot="trigger" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/jpeg文件，且不超过500kb (已选择个
              <strong>{{ imgLimit }}</strong
              >/10000 文件)
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormGroup = false" :disabled="groupLoading"
          >取消</el-button
        >
        <el-button
          type="primary"
          @click="submitUploadGroup()"
          :loading="groupLoading"
          >提交</el-button
        >
      </div>
    </el-dialog>
    <el-dialog :visible.sync="dialogVisible">
      <img :src="dialogImageUrl" alt="" width="100%" />
    </el-dialog>
    <el-dialog
      title="失败文件提示"
      :visible.sync="dialogTableVisibleFail"
      :close-on-click-modal="false"
      @close="turnGetList"
    >
      <el-table :data="failList" style="width: 100%; max-height: 600px">
        <el-table-column
          property="sName"
          label="姓名"
          align="left"
          show-overflow-tooltips
        ></el-table-column>
        <el-table-column property="iLoadCompleted" label="原因" align="left">
          <template slot-scope="scope"> 无效特征值 </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  getBase64,
  getFacePersonsListApi,
  personsUploadApi,
  addFacePersonsApi,
  editFacePersonsApi,
  delFacePersonsApi,
  getFacePersonsListNamesApi,
  getLastFaceApi,
  getFaceWaitingApi,
  getFaceCheckIdsApi,
  getFacePersonsApi,
  faceListExportUrlApi,
  clearAllUserApi,
} from "@/api/community/communityPerson";
import { downloadFile } from "@/api/file/file";
import ExcelUpload from "./component/ExcelUpload";
import Pagination from "@/components/Pagination";
import FileSaver from "file-saver";

import excelUtil from "@/utils/dealwithExcelUtil.js";
import { cnReg } from "@/utils/validate.js";

import { getPersonList,addPerson,editEventIdentity,getEventIdentity,fileUpload } from "@/api/community/person";

const rules = {
  sName: [
    {
      trigger: ["blur", "change"],
      required: true,
      message: "请输入中文名称",
      pattern: cnReg,
    },
  ],
  sTelephoneNumber: [
    {
      required: false,
      message: "手机号码不能为空",
      trigger: ["blur"],
    },
    {
      pattern: /^1[0-9]\d{9}$/,
      message: "请输入正确的号码",
      trigger: ["blur"],
    },
  ],
  sCertificateNumber: [
    {
      trigger: ["blur", "change"],
      required: false,
      message: "请填写身份证信息",
    },
    {
      pattern: /(^\d{18}$)|(^\d{15}$)/,
      message: "请输入正确的身份证",
      trigger: ["blur", "change"],
    },
  ],
  sBirthday: [
    {
      trigger: "blur",
      required: true,
      message: "请选择出生日期",
    },
  ],
  iAccessCardNumber: [
    {
      trigger: "blur",
      required: true,
      message: "请输入门禁卡号",
    },
  ],
};

export default {
  name: "CommunityPerson",
  components: { Pagination, ExcelUpload },
  data: function () {
    return {
      pickerOptions: {
        shortcuts: [
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      rules,
      hideUpload: false,
      fit: "contain",
      personData: { list: [], total: 0 },
      listQuery: {
        name: "",
        beginTime: "1970-01-01 00:00:00",
        endTime: "2021-08-11 23:59:59",
        type: "all",
        gender: "all",
        minAge: 0,
        maxAge: 100,
        accessCardNumber: 0,
        beginPosition: 0,
        endPosition: 19,
        limit: 20,
        page: 1,
        iLoadComplete: "1",
      },
      machineQuery: {
        page: 1,
        row: 10,
        communityId: "",
      },
      limitCount: 1,
      form: {},
      selectList: [],
      // 门禁A设备
      machine: {
        list: [],
        total: 0,
      },
      toMachinePerson: {
        personId: "",
        machineId: "",
      },
      fileList: [],
      dialogVisible: false,
      dialogFormVisible: false,
      dialogFormGroup: false,
      groupLoading: false,
      dialogImageUrl: "",
      uploadDialogVisible: false,
      fileForm: undefined,
      sTypeArr: [
        { name: "白名单", value: "whiteList" },
        { name: "黑名单", value: "blackList" },
        // {name:'访客',value:'tourist'},
      ],
      dateTime: [],
      srcList: [],
      fileListGroup: [],
      checkId: 0,
      failList: [],
      isAdd: "add",
      dialogTableVisibleFail: false, //失败文件
      singleLoading: false,
      percentage: 0,
      scaleTage: 0,
      intervalTime: null,
      showprogress: false,
      personStatus: [
        { name: "成功人员", value: "1" },
        { name: "等待人员", value: "0" },
        { name: "失败人员", value: "-1" },
      ],
    };
  },
  created() {
    this.doGetCommunityPersons();
  },
  watch: {
    dialogFormVisible: function (val) {
      if (val === false) {
        this.form = {
          personId: "",
          name: "",
          tel: "",
          idNumber: "",
          type: "",
          sLocalPicturePath: "",
        };
        this.fileList = [];
      }
    },
    showprogress: {
      handler(n, o) {
        if (n) {
          this.increase();
        } else {
          this.increaseend();
        }
      },
      deep: true,
    },
  },
  filters: {
    sType(val) {
      switch (val) {
        case "whiteList":
          return "白名单";
        case "blackList":
          return "黑名单";
        default:
          return "访客";
      }
    },
    iLoadCompleted(val) {
      switch (val) {
        case -1:
          return "失败";
        case 0:
          return "等待";
        case 1:
          return "成功";
      }
    },
  },
  methods: {
    changePage(val) {
      let [page, limit] = [val.page, val.limit];
      this.listQuery.beginPosition = page * limit - limit;
      this.listQuery.endPosition = page * limit - 1;
      this.doGetCommunityPersons();
    },
    doGetCommunityPersons() {
      this.listQuery.minAge = 0;
      this.listQuery.maxAge = 100;
      this.listQuery.beginTime =
        this.dateTime && this.dateTime[0]
          ? this.dateTime[0]
          : "1970-01-01 00:00:00";
      this.listQuery.endTime =
        this.dateTime && this.dateTime[1]
          ? this.dateTime[1]
          : this.$moment(this.$moment().endOf("day").unix() * 1000).format(
              "YYYY-MM-DD HH:mm:ss"
            );
      this.listQuery.beginTime = this.listQuery.beginTime.replace(/ /, " ");
      this.listQuery.endTime = this.listQuery.endTime.replace(/ /, " ");
      // if (this.listQuery.name) {
      //   getFacePersonsListNamesApi(this.listQuery).then((response) => {
      //     this.personData = { list: response.matchList, total: +response.numOfMatches };
      //     response.matchList.forEach((item) => {
      //       item.sLocalPicturePath = item.sLocalPicturePath+'?'+new Date().getTime();
      //     });
      //   });
      // }else {
      getPersonList(this.listQuery).then((response) => {
        this.personData.list = [];
        this.personData.total = 0;
        this.$nextTick(() => {
          this.personData = {
            list: response.matchList,
            total: +response.numOfMatches || 0,
          };
          response.matchList.forEach((item) => {
            item.sLocalPicturePath = item.sLocalPicturePath + "?" + new Date().getTime();
            item.sRegistrationTime = item.sRegistrationTime.replace(/T/g, " ");
          });
          // 请求上一页
          if (this.listQuery.page != 1 && this.personData.list.length == 0) {
            this.changePage({ page: this.listQuery.page - 1 });
          }
        });
      });
      // }
    },
    onSearch() {
      this.doGetCommunityPersons();
    },
    onReset() {
      this.listQuery = {
        name: "",
        beginTime: "1970-01-01 00:00:00",
        endTime: this.$moment(this.$moment().endOf("day").unix() * 1000)
          .format("YYYY-MM-DD HH:mm:ss")
          .replace(/ /g, " "),
        type: "all",
        gender: "all",
        minAge: 0,
        maxAge: 100,
        accessCardNumber: 0,
        beginPosition: 0,
        endPosition: 19,
        iLoadComplete: "1",
        limit: 20,
        page: 1,
      };
      this.dateTime = [];
      this.doGetCommunityPersons();
    },
    reset() {
      this.resetForm("form");
      this.form = {
        sCertificateType: "identityCard",
        sGender: "male",
        sType: "whiteList",
        iAccessCardNumber: 0,
        sBirthday: "1970-01-01",
        sAddress: "",
        sCertificateNumber: "",
        sHometown: "",
        sListType: "permanent",
        sName: "",
        sNation: "汉族",
        sNote: "",
        sTelephoneNumber: "",
        sType: "whiteList",
      };
      this.fileForm = undefined;
    },
    handleSelectionChange(value) {
      this.selectList = [];
      for (let i = 0; i < value.length; i++) {
        this.selectList.push({ id: value[i].id });
      }
    },
    // 添加人脸
    addCommunityPerson(msg) {
      this.fileListGroup = [];
      this.singleLoading = false;
      if (msg == 1) {
        this.isAdd = "add";
        this.dialogFormVisible = true;
        this.hideUpload = false;
        this.reset();
      } else {
        this.isAdd = "group";
        this.dialogFormGroup = true;
      }
    },
    deleteCommunityPerson(_row) {
      this.selectList = [{ id: _row.id }];
    },
    doDeleteCommunityPerson() {
      if (!this.selectList || this.selectList.length === 0) {
        this.$message.warning("请选择删除人员");
        return;
      }
      for (let i = 0; i < this.selectList.length; i++) {
        delFacePersonsApi(this.selectList[i].id)
          .then((res) => {
            if (i == this.selectList.length - 1) {
              this.$message.success("删除成功");
              this.doGetCommunityPersons();
              this.selectList = [];
            }
          })
          .catch((err) => {
            if (i == this.selectList.length - 1) {
              this.$message.success("删除成功");
              this.doGetCommunityPersons();
              this.selectList = [];
            }
          });
      }
    },
    doDeleteCommunityPersonSelect() {
      if (!this.selectList || this.selectList.length === 0) {
        this.$message.warning("请选择删除人员");
        return;
      }
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, `此操作将永久删除所选`),
          h("i", { style: "color: #f00" }, this.selectList.length),
          h("span", null, "个人员, 是否继续?"),
        ]),
        showCancelButton: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        beforeClose: (action, instance, done) => {
          if (action === "confirm") {
            console.log("1111");
            done();
          } else {
            done();
          }
        },
      }).then((action) => {
        // console.log(action);
        for (let i = 0; i < this.selectList.length; i++) {
          delFacePersonsApi(this.selectList[i].id)
            .then((res) => {
              if (i == this.selectList.length - 1) {
                this.$message.success("删除成功");
                this.doGetCommunityPersons();
                this.selectList = [];
              }
            })
            .catch((err) => {
              if (i == this.selectList.length - 1) {
                this.$message.success("删除成功");
                this.doGetCommunityPersons();
                this.selectList = [];
              }
            });
        }
      });
      return false;

      this.$confirm(
        `此操作将永久删除所选${this.selectList.length}个人员, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          for (let i = 0; i < this.selectList.length; i++) {
            delFacePersonsApi(this.selectList[i].id)
              .then((res) => {
                if (i == this.selectList.length - 1) {
                  this.$message.success("删除成功");
                  this.doGetCommunityPersons();
                  this.selectList = [];
                }
              })
              .catch((err) => {
                if (i == this.selectList.length - 1) {
                  this.$message.success("删除成功");
                  this.doGetCommunityPersons();
                  this.selectList = [];
                }
              });
          }
        })
        .catch(() => {
          // this.$message.info("已取消删除");
        });
    },
    doDeleteCommunityPersonAll() {
      this.$confirm("此操作将永久删除所有人员, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          clearAllUserApi().then((res) => {
            // console.log(res);
            this.$message.success("删除成功");
            this.doGetCommunityPersons();
          });
        })
        .catch(() => {
          // this.$message.info("已取消删除");
        });
    },
    // 修改
    editCommunityPerson(_row, _index) {
      this.singleLoading = false;
      this.reset();
      this.isAdd = "edit";
      this.dialogFormVisible = true;
      this.form = this.$fn.deepCopy(_row);
      this.fileForm = 1;
      this.fileList = [
        {
          name: "图片",
          url: this.localOrigin + _row.sLocalPicturePath,
        },
      ];
      if (_row.sLocalPicturePath) {
        this.fileList = [
          {
            name: "图片",
            url:this.localOrigin + _row.sLocalPicturePath,
          },
        ];
        this.hideUpload = true;
      } else {
        this.hideUpload = false;
      }
    },
    // 提交单个的
    saveCommunityPersonInfo() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          // let other = {"sAddress":"","sHometown":"","sListType":"permanent","sNation":"汉族","sNote":"undone","iFaceDBId":-2}
          // this.form = Object.assign({},this.form,other);
          if (!this.fileForm) {
            this.msgError("请上传头像");
            return false;
          }
          this.form.sNote = "undone";
          this.singleLoading = true;
          if (this.isAdd == "add") {
            this.getSingle(this.form, 0, this.fileForm);
          } else {
            this.form.sLocalPicturePath = undefined;
            editFacePersonsApi(this.form, this.form.id).then((response) => {
              this.dialogFormVisible = false;
              // console.log(response);
              if (this.fileForm == 1) {
                // 没有修改头像
                this.$message.success("修改成功");
                this.doGetCommunityPersons();
                this.singleLoading = false;
              } else {
                this.uploadFileImg(response.sLocalPicturePath);
                // this.doGetCommunityPersons();
              }
            });
          }
        } else {
          this.singleLoading = false;
          // console.log(valid);
        }
      });
    },
    // 同时提交图片
    uploadFileImg(path, oldId) {
      let formData = new FormData();
      formData.append("file", this.fileForm);
      personsUploadApi(formData, path)
        .then((response) => {
          this.doGetCommunityPersons();
        })
        .catch((err) => {
          if (this.isAdd == "add") {
            this.form.sNote = "";
            let allP = [];
            // 循环请求 是否添加成功或者失败
            for (let i = 0; i < 6; i++) {
              if (i == 0) {
                allP.push(
                  new Promise((resolve, reject) => {
                    editFacePersonsApi(this.form, oldId)
                      .then((response) => {
                        resolve(response);
                      })
                      .catch((err) => {
                        resolve(err);
                      });
                  })
                );
              } else {
                allP.push(
                  new Promise((resolve, reject) => {
                    setTimeout(() => {
                      getFacePersonsApi(oldId, new Date().getTime())
                        .then((response) => {
                          resolve(response);
                        })
                        .catch((err) => {
                          resolve(err);
                        });
                    }, 200 * i);
                  })
                );
              }
            }
            Promise.all(allP).then((res) => {
              // 有失败的就删除掉
              let flag = false;
              this.singleLoading = false;
              for (let v of res) {
                if (v.iLoadCompleted == -1) {
                  flag = true;
                }
              }
              if (flag) {
                delFacePersonsApi(oldId)
                  .then((res) => {})
                  .catch((err) => {
                    this.$message.error("获得照片特征值失败，请更换照片");
                  });
              } else {
                this.dialogFormVisible = false;
                this.$message.success("新增成功");
                this.turnGetList();
              }
            });
          } else {
            this.singleLoading = false;
            this.turnGetList();
            this.$message.success("修改成功");
            this.dialogFormVisible = false;
          }
        });
    },
    doDownloadFile() {
      let params = {
        beginTime: "",
        endTime: "",
        page: -1,
        limit: -1,
        name: "",
      };
      faceListExportUrlApi(params).then((res) => {
        let downLoadfile = process.env.VUE_APP_BASE_URL + res.url;
        this.download(downLoadfile, new Date().getTime());
      });
    },
    download(href, title) {
      const a = document.createElement("a");
      a.setAttribute("href", href);
      a.setAttribute("download", title);
      a.click();
    },
    // 获取单个图片信息
    getFile(file, fileList) {
      const isLt05M = 1024 * 1024 * 0.5;
      let hasBig = file.size > isLt05M;
      if (hasBig) {
        this.fileList = [];
        this.$message.error("上传头像图片大小不能超过 500K!");
        return false;
      }
      this.fileForm = file.raw;
      let name = file.name.split(".");
      if (this.form.sName === "") {
        this.form.sName = name[0];
      }
      this.hideUpload = fileList.length >= this.limitCount;
    },
    handleRemove(file, fileList) {
      this.fileForm = undefined;
      this.hideUpload = fileList.length >= this.limitCount;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // ========================批量上传========================
    handleRemoveGroup(file, fileList) {
      this.fileListGroup = fileList;
    },
    handleSuccessGroup(response, file) {
      const isLt05M = 1024 * 1024 * 0.5;
      // let hasBig = file.some((v) => {
      //   return v.size > isLt05M
      // })
      // if (hasBig) {
      //   this.$message.error('上传头像图片大小不能超过 0.5MB!');
      // }
      this.fileListGroup = file.filter((v, i) => {
        return v.size <= isLt05M;
      });
    },
    handleExceed(file, fileList) {
      this.$message.warning("最大限度上传10000张");
    },
    // 点击批量添加
    submitUploadGroup() {
      if (this.fileListGroup.length > 0) {
        this.groupLoading = true;
        // 获取最后一个id
        let p1 = new Promise((resolve, reject) => {
          getLastFaceApi()
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              this.groupLoading = false;
            });
        });
        // 获取已有数量
        let p2 = new Promise((resolve, reject) => {
          getFaceWaitingApi().then((res) => {
            let numOfWaiting = res.numOfWaiting;
            resolve(res);
          });
        });
        // 执行上传
        Promise.all([p1, p2]).then((res) => {
          this.checkId = res[0].id;
          this.uploadGroupFileOne();
        });
      } else {
        this.msgError("请添加文件!");
      }
    },
    // 多个图片单独请求
    uploadGroupFileOne() {
      this.showprogress = true;
      this.percentage = 1;
      this.scaleTage = 100 / this.fileListGroup.length;
      let asyncFunc = (params, i, c_files) => {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (i % 5 == 0) {
              getFaceWaitingApi(new Date().getTime()).then(() => {
                setTimeout(() => {
                  getFaceWaitingApi(new Date().getTime()).then(() => {
                    setTimeout(() => {
                      this.getSingle(params, i, c_files);
                      resolve();
                    }, 200);
                  });
                }, 200);
              });
            } else {
              this.getSingle(params, i, c_files);
              resolve();
            }
          }, 200);
        });
      };
      let getFunc = async () => {
        for (let i = 0; i < this.fileListGroup.length; i++) {
          let params = {
            iAccessCardNumber: 0,
            sAddress: "",
            sBirthday: "1970-01-01",
            sCertificateNumber: "",
            sCertificateType: "identityCard",
            sGender: "unset",
            sHometown: "",
            sListType: "permanent",
            sName: this.fileListGroup[i].name.replace(
              /.(jpg|jpeg|png|bmp|gif)/,
              ""
            ),
            sNation: "汉族",
            sNote: "undone",
            sTelephoneNumber: "",
            sType: "whiteList",
          };
          await asyncFunc(params, i, this.fileListGroup[i].raw);
        }
      };
      getFunc();
    },
    // 循环单个请求中
    getSingle(params, b_i, c_files) {
      // 多个异步分开处理 先新增 再上传图片 再修改
      let hasRes = {};
      let a = () => {
        return new Promise((resolve, reject) => {
          addFacePersonsApi(params).then((response) => {
            hasRes = response;
            resolve(response);
          });
        });
      };

      let b = () => {
        return new Promise((resolve, reject) => {
          let formData = new FormData();
          formData.append("file", c_files);
          personsUploadApi(formData, hasRes.sLocalPicturePath)
            .then((res) => {
              resolve(res);
            })
            .catch((err) => {
              resolve(err);
            });
        });
      };

      let c = () => {
        return new Promise((resolve, reject) => {
          params.sNote = "";
          editFacePersonsApi(params, hasRes.id)
            .then((res) => {
              // 请求完数组队列,最后一项需要检验
              if (this.isAdd == "add") {
                // 单个添加 获取特征值
                getLastStatus(res);
              } else {
                if (b_i == this.fileListGroup.length - 1) {
                  // 多组添加获取特征值
                  this.percentage = 100;
                  getLastStatus(res);
                } else {
                  this.percentage = accAdd(this.percentage, this.scaleTage);
                }
              }
              resolve(res);
            })
            .catch((err) => {
              this.groupLoading = false;
            });
        });
      };

      Promise.resolve()
        .then(() => {
          return a();
        })
        .then(() => {
          return b();
        })
        .then(() => {
          return c();
        })
        .catch(() => {
          return c();
        });

      // 小数相加
      function accAdd(arg1, arg2) {
        var r1, r2, m;
        try {
          r1 = arg1.toString().split(".")[1].length;
        } catch (e) {
          r1 = 0;
        }
        try {
          r2 = arg2.toString().split(".")[1].length;
        } catch (e) {
          r2 = 0;
        }
        m = Math.pow(10, Math.max(r1, r2));
        return (arg1 * m + arg2 * m) / m;
      }

      let _this = this,
        showTime = 12000,
        showTime_i = 4;
      // 配置单个和多个的时间间隔
      if (this.isAdd == "add") {
        showTime = 6000;
        showTime_i = 2;
      }
      function getLastStatus(data) {
        let instance = _this.$notify.success({
          title: "提示",
          message: "正在获取特征值中",
          showClose: false,
          duration: 0,
        });
        setTimeout(() => {
          _this.showprogress = false;
        }, 1000);
        // 循环请求最后一个 循环间隔获取状态
        for (let i = 0; i < showTime_i; i++) {
          setTimeout(() => {
            getFacePersonsApi(data.id, new Date().getTime()).then((re) => {
              if (i == showTime_i - 1) {
                instance.close();
                _this.uploadFileImgGroup();
              }
            });
          }, 3000 * i);
        }
      }
    },
    uploadFileImgGroup() {
      this.turnGetList();
      this.dialogFormGroup = false;
      this.groupLoading = false;
      this.dialogFormVisible = false;
      this.singleLoading = false;
      return false;
      // 请求完了检查失败的图片
      //TODO:在获取人员列表
      getFaceCheckIdsApi({ id: this.checkId })
        .then((response) => {
          this.failList = response;
          if (this.failList.length > 0) {
            if (this.isAdd == "add") {
              this.singleLoading = false;
              this.$message.error("获得照片特征值失败，请更换照片");
            } else {
              this.dialogTableVisibleFail = true;
              // this.turnGetList();
            }
          } else {
            if (this.isAdd == "add") {
              this.$message.success("新增成功");
            }
            this.dialogFormVisible = false;
            this.turnGetList();
          }
          this.dialogFormGroup = false;
          this.groupLoading = false;
        })
        .catch((err) => {
          this.turnGetList();
          this.dialogFormGroup = false;
          this.groupLoading = false;
        });
    },
    turnGetList() {
      this.doGetCommunityPersons();
      setTimeout(() => {
        this.doGetCommunityPersons();
      }, 3000);
    },
    onClose() {
      this.$refs["dataForm"].resetFields();
    },
    // 更新进度条数量
    increase() {
      // this.intervalTime = setInterval(() => {
      // if (this.percentage > 99) {
      //     this.percentage = 100;
      // }else {
      //   this.percentage += 5;
      // }
      // }, 300);
    },
    // 进度条结束
    increaseend() {
      this.percentage = 100;
      clearInterval(this.intervalTime);
    },
  },
  computed: {
    imgLimit() {
      return this.fileListGroup && this.fileListGroup.length;
    },
    localOrigin () {
      return location.origin;
    }
  },
  destroyed() {
    clearInterval(this.intervalTime);
  },
};
</script>
<style lang="scss" scoped>
/deep/ .hide .el-upload--picture-card {
  display: none;
}
.el-form-box {
  /deep/ {
    .numrule input::-webkit-outer-spin-button,
    .numrule input::-webkit-inner-spin-button {
      -webkit-appearance: none !important;
    }
    .numrule input[type="number"] {
      -moz-appearance: textfield;
    }
  }
}

.pro-loading {
  margin: 0 0 10px 70px;
}
</style>
